package com.example.practiceopenglfortexture;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("native-lib");
    }

    TCamera2 tCamera2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkPermission();

        // for OpenGL
        GLSurfaceView glSurfaceView = findViewById(R.id.glSurfaceView);
        glSurfaceView.setEGLContextClientVersion(2);

        // for camera
        tCamera2 = new TCamera2(MainActivity.this, glSurfaceView);

        // for render
        TRenderer tRenderer = new TRenderer(tCamera2);
        glSurfaceView.setRenderer(tRenderer);
        glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        tCamera2.stopPreview();
    }

    private void checkPermission() {
        String[] permissions = new String[]{
                Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE
        };
        List<String> mPermissionList = new ArrayList<>();

        mPermissionList.clear();
        for (String permission1 : permissions) {
            if (ContextCompat.checkSelfPermission(MainActivity.this, permission1) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permission1);
            }
        }
        if (mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了
            Toast.makeText(MainActivity.this, "已经授权", Toast.LENGTH_SHORT).show();
        } else {//请求权限方法
            String[] permission = mPermissionList.toArray(new String[0]);//将List转为数组
            ActivityCompat.requestPermissions(MainActivity.this, permission, 2);
        }
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native String stringFromJNI();
}
